package com.teligen.zkdb.zk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teligen.zkdb.db.DbConfig;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ZookeeperUtil {

    @Value("${zk.host}")
    private String zkHost;

    private ZkClient zkClient;

    private ZkClient getZkClient(){
        if (zkClient == null){
            zkClient = new ZkClient(zkHost);
        }
        return zkClient;
    }


    public DbConfig readDbConfig(){
        String path = getDbPath();
        if (!getZkClient().exists(path)){
            return null;
        }
        String configStr = getZkClient().readData(path).toString();
        DbConfig dbConfig = JSONObject.parseObject(configStr, DbConfig.class);
        return dbConfig;
    }


    public void watchDbConfig(DataChange dataChange){
        getZkClient().subscribeDataChanges(getDbPath(), new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                DbConfig dbConfig = JSONObject.parseObject((String) o, DbConfig.class);
                dataChange.dataChange(s,dbConfig);
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {

            }
        });
    }

    private String getDbPath(){
        return "/zk/db";
    }

    private String getParentDbPath(){
        return "/zk";
    }


    public void initDbConfigOne(){
        DbConfig dbConfig = new DbConfig();
        dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
        dbConfig.setUrl("jdbc:mysql://localhost:3306/blog_system?serverTimezone=UTC");
        dbConfig.setPassword("root");
        dbConfig.setUsername("root");
        initDbConfig(dbConfig);
    }


    public void initDbConfigTwo(){
        DbConfig dbConfig = new DbConfig();
        dbConfig.setDriverClassName("com.mysql.jdbc.Driver");
        dbConfig.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC");
        dbConfig.setPassword("root");
        dbConfig.setUsername("root");
        initDbConfig(dbConfig);
    }

    public void initDbConfig(DbConfig dbConfig){
        String path = getDbPath();
        if (!getZkClient().exists(path)){
            getZkClient().createPersistent(path,true);
        }
        getZkClient().writeData(path,JSONObject.toJSONString(dbConfig));
    }



}
